package com.yx.shop.dao.impl;

import com.yx.shop.dao.ProductDao;
import com.yx.shop.entitly.PageBean;
import com.yx.shop.entitly.Product;
import com.yx.shop.entitly.Type;
import com.yx.shop.utils.JDBCUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @Classname ProductDaoImpl
 * @Description TODO:
 * @Date 2021/05/07 17:20
 * @Created by yx
 */
public class ProductDaoImpl implements ProductDao {
    private QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
    @Override
    public List<Product> getProductByTid(PageBean page, Integer tid) {
        String sql = "select * from product where tid=? limit ?,?;";
        try {
            return queryRunner.query(sql,new BeanListHandler<>(Product.class),tid,page.getStartRows(),page.getPageSize());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Long getCount(Integer tid) {
        String sql = "select count(pid) from product where tid = ?;";
        try {
           return queryRunner.query(sql,new ScalarHandler<>(),tid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Product getById(Integer pid) {
        String sql = "SELECT pid,product.tid AS tid,pname,ptime,pimage,pprice,pstate,pinfo,tname,tinfo FROM product INNER JOIN TYPE ON product.tid = TYPE.tid where pid=?;";
        try {
            Map<String, Object> query = queryRunner.query(sql, new MapHandler(), pid);
            //如果查询到数据map集合为null,不封装数据,避免出现返回空对象
            if (query!=null){
                //2.创建封装数据的实体类 product中有1个Type的类型属性值存在
                Product product = new Product();
                Type type = new Type();
                //3.通过beanutils工具类封装数据
                BeanUtils.populate(product,query);
                BeanUtils.populate(type,query);
                //4.把封装的数据加入product
                product.setType(type);
                return product;
            }


        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}
